var over = 0;
var id = 0;
var destinationNode = [];    // 发货目的地
var colourList = [];         // 颜色列表
var printData = {};          // 打印数据
var maxRowNum = 0;           // 每色最大行数
var rowsPerPage = 21;        // 每页显示的行数（包含小计行）
var totalPageSize = 0;       // 总页数
var colourNumPerPage = 0;    // 每页颜色数
var coloumNumPerColour = 0;  // 每色显示列数
var pageBreakPoint = [];     // 分页点
var _w = 542;                // 每色每列组的宽度
var _w01 = 271;              // 每色每列组的宽度

var thisPage = {
    // 初始化页面
    OnPageLoad: function () {
        thisPage.PageInit();
    },
    GetFilters: function () {
        var _params = {};
        _params["HeaderId"] = parseInt(id);
        _params['CurrentUserId'] = parseInt(parent.$("#UserId").val());
        _params['WorkFlowId'] = parent.$("#WorkFlowId").val() === '' ? 0 : parseInt(parent.$("#WorkFlowId").val());
        return JSON.stringify(_params);
    },
    PageInit: function () {
        $.ajax({
            type: "POST",
            url: window.basePath + "/trade/production_instruction/print/fetch.html",
            timeout: 30 * 1000,
            data: thisPage.GetFilters(),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            beforeSend: function () {
            }
        }).done(function (data) {
            let item = data.HeaderEntity;
            $("#SaledByName").text(item.saledByName);
            $("#ContractNo").text(item.contractNo);
            $("#SuitStyleNo").text(item.suitStyleNo);
            $("#SuitProductName").text(item.suitProductName);
            $("#IssueDate").text(item.issueDate === null ? "" : item.issueDate);
            $("#TotalQuantity").text(item.totalQuantity);
            $("#SampleQuantity").text(item.sampleQuantity);
            //$("#TradeModeName").text(item.tradeModeName);
            $("#ShippingSchedule").text(item.shippingSchedule);
            //let _desc = item.description === null ? "" : item.description.replace(/\n/g, '<br/>');
            let _desc = item.description === null ? ("贸易模式：" + item.tradeModeName) : ("<div style='margin-bottom:6px;'>贸易方式：" + item.tradeModeName + "</div>" + item.description.replace(/\n/g, '<br/>'));
            $("#Description").html(_desc);
            $("#PrintedDate").text(getCurrentDate());                 // 打印日期
            //let _dh = $("#header_left").height();
            //$("#Description").css({height: _dh - 20});

            // 目的地
            destinationNode = data.DestinationNode;
            // 颜色数据
            colourList = data.ColourList;
            printData = data.LinesList;
            // 每色最大行数
            maxRowNum = data.MaxRowNumPerColour;
            if (printData !== null) {
                thisPage.SetPrintPageData();
            } else {
                $('#loading').hide();
            }
        }).fail(function (data) {
            $('#loading').hide();
            ajaxError(data, 1);
        }).always(function () {
        });
    },
    // 根据颜色数决定打印页面
    SetPrintPageData: function () {
        if (colourList === null || colourList.length === 0) {
            totalPageSize = 0;
        } else {
            /*
             * 如果有发货目的地, 那么每页页面只能显示2个颜色列，后面的被目的地填充
             * 没有目的地，每个页面显示4个颜色列
             */
            if (destinationNode.length > 0) {
                if (maxRowNum < rowsPerPage) {
                    totalPageSize = Math.ceil(colourList.length / 2);
                    colourNumPerPage = 2;    // 每页颜色数
                }
                // 如果每色的行数正好等于每页显示的行数，为了给小计行留下空间，让每页显示的最大行 - 1
                if (maxRowNum === rowsPerPage) {
                    totalPageSize = colourList.length;
                    colourNumPerPage = 1;    // 每页颜色数
                }
                if (maxRowNum > rowsPerPage) {
                    totalPageSize = colourList.length;
                    colourNumPerPage = 1;    // 每页颜色数
                }
            } else {
                if (maxRowNum < rowsPerPage) {
                    totalPageSize = Math.ceil(colourList.length / 4);
                    colourNumPerPage = 4;    // 每页颜色数
                }
                // 如果每色的行数正好等于每页显示的行数，为了给小计行留下空间，让每页显示的最大行 - 1
                if (maxRowNum === rowsPerPage) {
                    totalPageSize = Math.ceil(colourList.length / 2);
                    colourNumPerPage = 2;    // 每页颜色数
                }
                if (maxRowNum > rowsPerPage) {
                    totalPageSize = Math.ceil(colourList.length / 2);
                    colourNumPerPage = 2;    // 每页颜色数
                }
            }
        }

        // 显示明细数据
        linesHandler.datalist = printData;
        $("#LineDataArea").empty();
        linesHandler.BuildDataTable(printData);
        $('#loading').hide();
    },
    // html打印
    DoPreview: function () {
        window.print();
        /*
         let _html_heade_content = "<!DOCTYPE html><html><head>" + window.document.head.innerHTML + "</head><body>";
         let _body_content = window.document.body.innerHTML;
         let  _print_header_start = "<!--headerstart-->";
         let _print_header_end = "<!--headerend-->";
         var _print_header_content = _body_content.substr(_body_content.indexOf(_print_header_start));
         _print_header_content = _print_header_content.substring(18, _print_header_content.indexOf(_print_header_end));
         let _print_footer_start = "<!--footerstart-->";
         let  _print_footer_end = "<!--footerend-->";
         let _html_footer_content = _body_content.substr(_body_content.indexOf(_print_footer_start));
         _html_footer_content = _html_footer_content.substring(18, _html_footer_content.indexOf(_print_footer_end));
         
         //_html_content = _html_content + _print_header_content + "<tbody>";
         let _html_body_content = "";
         $("#LineDataArea").find("tr").each(function (index) {
         _html_body_content += _print_header_content + "<tbody>";
         _html_body_content += $(this).prop("outerHTML");
         _html_body_content += "<tbody>";
         });
         let _html_content = _html_heade_content + _html_body_content + "<tbody>" + _html_footer_content + "</body></html>";
         console.info(_html_content);
         let _iframe = document.getElementById('PrintFrame');
         _iframe.innerHTML = "";   // 首先清空，然后重新写入
         let doc = _iframe.contentWindow.document;
         //doc.open();
         doc.write(_html_content);
         doc.close();
         console.info(_html_content);
         _iframe.focus();    // 获得焦点后才能打印
         //_iframe.contentWindow.focus();
         //_iframe.contentWindow.print();*/
    },
    Export: function () {
        $("#export_form").attr("action", parent.basePath + "/trade/production_instruction/export_to_excel.html");
        $("#ExportHeaderId").val(id);
        $("#export_form").submit();
    }
};

//-----------------------------------------------------------------------------
// 明细处理部分
//-----------------------------------------------------------------------------
var linesHandler = {
    datalist: [],
    BuildDataTable: function (result) {
        if (totalPageSize === 0)
            return;

        let firstrow = true;
        let currentrows = 0;
        let coloumns = 0;
        let subTotal = {};

        let _col_width = Math.round(_w01 / destinationNode.length);
        var content = '<div class="cell_coloumn" style="margin-left:-1px; margin-top:10px;"><table>';
        content += '<thead><tr>';
        content += '<th class="cell" style="width: ' + (_w - _col_width * destinationNode.length - 150 - destinationNode.length + 1) + 'px;">颜色</th>';
        content += '<th class="cell" style="width: 70px;">尺寸</th>';
        content += '<th class="cell" style="width: 80px;">合同数</th>';
        for (let i = 0; i < destinationNode.length; i++) {
            content += '<th class="cell" style="width:' + _col_width + 'px;">' + destinationNode[i].destination + '</th>';
        }
        content += '</tr></thead><tbody>';
        for (let i = 0; i < result.length; i++) {
            if (parseInt(result[i].rowFlag) === 0) {
                content += '<tr>';
                if (firstrow) {
                    content += '<td class="cell" rowspan="' + (rowsPerPage - 1) + '">' + formatNullData(result[i].colourName) + '<br />(' + formatNullData(result[i].colourNumber) + ')</td>';
                }
                content += '<td class="cell">' + formatNullData(result[i].suitSizeName) + '</td>';
                content += '<td class="cell">' + formatNullData(result[i].rowSubTotal) + '</td>';
                for (let z = 0; z < destinationNode.length; z++) {
                    let _destination = destinationNode[z].destination;
                    let _t = false;
                    $.each(result[i].schemaMemoJson, function (index, data) {
                        if (data.Destination === _destination) {
                            content += '<td class="cell">' + formatNullData(data.Quantity) + '</td>'; // 目的地分配数量
                            _t = true;
                            return false;
                        }
                    });
                    if (_t === false)
                        content += '<td class="cell"></td>'; // 目的地分配数量
                }
                firstrow = false;
                content += '</tr>';
                currentrows = currentrows + 1;
                //datalist.shift();   // 删除使用后的数据
            }
            if (parseInt(result[i].rowFlag) === 1) {
                subTotal = result[i];
                //datalist.shift();   // 删除使用后的数据
                break;
            }
            if (currentrows === (rowsPerPage - 1) && parseInt(result[i + 1].rowFlag) === 0) {
                break;
            }
        }
        if (currentrows >= (rowsPerPage - 1)) {
            coloumns += 1;
        } else {
            // 补充空格
            for (let i = currentrows; i < (rowsPerPage - 1); i++) {
                content += '<tr>';
                content += '<td class="cell">&nbsp;</td>';
                content += '<td class="cell">&nbsp;</td>';
                for (let z = 0; z < destinationNode.length; z++) {
                    content += '<td class="cell">&nbsp;</td>';
                }
                content += '</tr>';
            }
        }

        // 小计行
        if (!$.isEmptyObject(subTotal)) {
            content += '<tr>';
            content += '<td class="cell" colspan="2" style="font-weight:bold;">TOTAL</td>';
            content += '<td class="cell" style="font-weight:bold;">' + subTotal.rowSubTotal + '</td>';
            for (let z = 0; z < destinationNode.length; z++) {
                let _destination = destinationNode[z].destination;
                let _t = false;
                $.each(subTotal.schemaMemoJson, function (index, data) {
                    if (data.Destination === _destination) {
                        content += '<td class="cell" style="font-weight:bold;">' + formatNullData(data.Quantity) + '</td>'; // 目的地分配数量
                        _t = true;
                        return false;
                    }
                });
                if (_t === false)
                    content += '<td class="cell"></td>'; // 目的地分配数量
            }
            content += '</tr>';
            subTotal = {};
            linesHandler.datalist.splice(0, currentrows + 1);
        } else {
            content += '<tr>';
            content += '<td class="cell" colspan="2" style="font-weight:bold;">TOTAL</td>';
            content += '<td class="cell" style="font-weight:bold;">&nbsp;</td>';
            for (let z = 0; z < destinationNode.length; z++) {
                content += '<td class="cell"></td>'; // 目的地分配数量
            }
            linesHandler.datalist.splice(0, currentrows);
        }
        content += '</tbody></tbale></div>';
        $("#LineDataArea").append(content);
        content = '';
        //console.info(datalist);
        // 递归调用（保留最后一行总计）
        if (linesHandler.datalist.length > 1) {
            linesHandler.BuildDataTable(linesHandler.datalist);
        }
    },
    InsertPageBreak: function () {
        if (pageBreakPoint.length > 0 && pageBreakPoint[0] === linesHandler._rows) {
            pageBreakPoint = [];
        }
        if ($("#tabData tr.row__clicked").length > 0) {
            var content = $('<tr class="page-break"><td colspan="11" style="text-align:center;"><p>-- 分页符 --</p></td></tr>');
            $("#tabData tr.row__clicked").after(content);
            // 增加分页点
            pageBreakPoint.push(parseInt($("#tabData tr.row__clicked").attr("sequence")));
        } else {
            ShowErrorMessagePanel('请选择要进行分页的位置。');
            $(".error-msg").css({top: '2px'});
        }
    }
};
//-----------------------------------------------------------------------------
// 页面初始化
//-----------------------------------------------------------------------------
function onPageReady() {
    id = jQuery.url.param("id");

    // 用于导出excel文件
    $("#export_iframe").remove();
    let $iFrame = $('<iframe id="export_iframe" name="_export_iframe" style="position:absolute; top:-9999px; left:-9999px" src="javascript:false"></iframe>');
    $("body").append($iFrame);
    let $form = $('<form id="export_form" name ="_export_form" method="POST" action ="" target="_export_iframe" style="position:absolute; top:-1200px; left:-1200px"></form>');
    $('<input type="hidden" id="ExportHeaderId" name="_ExportHeaderId" value="" />').appendTo($form);
    $("body").append($form);
    // 监听iframe回调（submit()后设置iFrame加载完成事件，用于获取表单提交成功后的结果,iFrame.load(loadFunc());）
    $iFrame.on("load", function () {
        let contentWin = document.getElementById("export_iframe").contentWindow;
        let backBodyText = contentWin.document.body.innerText;
    });

    thisPage.OnPageLoad();
}

// 画面大小或者位置移动
function onPageResize() {
}
